package com.fingard.dsp.bank.directbank.fjnx12;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.DirectHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.dsp.bank.directbank.bocom13.BOCOM13Base;
import com.fingard.dsp.bank.directbank.bocom13.BOCOM13Header;
import com.fingard.dsp.bank.directbank.bocom13.util.JavaMD5;
import com.fingard.dsp.bank.directbank.bocom13.util.Mac;
import com.fingard.dsp.bank.directbank.cmb02.util.SignUtil;
import com.fingard.dsp.bank.directbank.fjnx12.FJNX12Base;
import com.fingard.dsp.bank.helpers.FileType;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.bank.syncfile.FileItem;
import com.fingard.dsp.task.command.SyncReceipt;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.net.TcpReceiver;
import com.fingard.net.listener.SocketReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.GZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class FJNX12AcceptNotice extends FJNX12Base implements IAcceptNotice {

    @Override
    public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {
        NoticeResp resp = new NoticeResp();
        String tmpStrReq = pNtReq.getReqString();
        WriteBankLogLn("接收到请求：" + pNtReq.getFullString());
        String tmpRespStr;
        byte[] tmpBytesSend = null;
        try {
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            String insuranceType = getBankConfig().getValueAsString("insuranceType");
            String downFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + "1034/" + insuranceType;

            if (tmpStrReq.contains("<?xml")) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrReq, tmpSbMsg);
                String transCode = tmpBkReader.getFirstText("/FILEREQ/MAIN/TRANSCODE");
                WriteBankLogLn2("异步通知交易代码:" + transCode);

                if ("1034".equals(transCode)) {
                    String fileName = tmpBkReader.getFirstText("/FILEREQ/MAIN/FILENAME");
                    String transDate = tmpBkReader.getFirstText("/FILEREQ/MAIN/TRANSRDATE");
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
                    xmlWriter.writeStartElement("FILERSP");
                    xmlWriter.writeStartElement("MAIN");
                    xmlWriter.writeElementString("TRANSRNO", getQryTransID());
                    xmlWriter.writeElementString("TRANSCODE", "2034");

                    String returnFilePath = downFilePath + fileName;
                    boolean existFile = false;
                    if (FileHelper.existFile(returnFilePath)) {
                        existFile = true;
                        xmlWriter.writeElementString("RESULTCODE", "0000");
                        xmlWriter.writeElementString("ERRINFO", "文件接收成功");
                    } else {
                        xmlWriter.writeElementString("RESULTCODE", "FAIL");
                        xmlWriter.writeElementString("ERRINFO", "FTP中未找到回盘文件" + fileName);
                    }
                    xmlWriter.writeEndDocument();
                    tmpRespStr = xmlWriter.toXmlString();

                    // 报文头：包长(6)+交易码(4)+密钥版本号(16)
                    byte[] tmpBytesBody = tmpRespStr.getBytes(getCharset());

                    String reqStrLength = String.format("%-6s", tmpBytesBody.length);
                    String trdCode = "2034";
                    String keyVersion = getBankConfig().getValueAsString("keyVersion");
                    String tmpHead = reqStrLength + trdCode + keyVersion;
                    byte[] tmpBytesHead = tmpHead.getBytes(getCharset());

                    tmpBytesSend = new byte[tmpBytesHead.length + tmpBytesBody.length];
                    System.arraycopy(tmpBytesHead, 0, tmpBytesSend, 0, tmpBytesHead.length);
                    System.arraycopy(tmpBytesBody, 0, tmpBytesSend, tmpBytesHead.length, tmpBytesBody.length);

                    String tmpResultFileName = "2034_" + transDate + "_" + fileName + ".xml";
                    String tmpResultFilePath = getNotifyDataDirectory() + File.separator + tmpResultFileName;
                    WriteBankLogLn2("待存入本机文件确认报文路径:" + tmpResultFilePath);
                    WriteBankLogLn2("待存入本机文件确认报文:\r\n" + tmpHead + tmpRespStr);
                    FileHelper.writeFile(tmpResultFilePath, tmpHead + tmpRespStr, getCharset());

                    // FTP上存在该文件，则下载到本地
                    if (existFile) {
                        String localDownloadFilePath = createTempFileDirectory(transDate) + File.separator + "batrec" + File.separator + fileName;
                        MixFtp mixFtp = new MixFtp(ftpSet);
                        FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(downFilePath, fileName, localDownloadFilePath);
                        if (!ftpReceiver.isCompleted) {
                            WriteBankLogLn2(ftpReceiver.connMsg);
                        } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                            WriteBankLogLn2("E9999-文件" + fileName + "下载失败！");
                        } else {
                            WriteBankLogLn2("批量代收回盘文件下载成功！");
                            WriteBankLogLn2("批量代收回盘文件保存本机路径:" + localDownloadFilePath);
                        }
                    }
                }
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }

        resp.respBytes = tmpBytesSend;
        return resp;
    }

    @Override
    public void getContentLength(SocketReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1 && p_receiver.readedLength >= 6) {
            String tmpHead = new String(p_receiver.reqBytes, 0, 6, getCharset());
            p_receiver.contentLength = Integer.parseInt(tmpHead.trim());
            p_receiver.contentStartIndex = 26;
        }
    }
}